'use strict'

import { app, protocol, BrowserWindow ,ipcMain, Menu, Tray } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let tray = null;
let timer_arr;
let meout_arr;
let mainWindow;

let setToolsTitle =
  process.env.NODE_ENV === "development" ? "AQBMTJ" : "数据所安全保密套件";

import path from "path"

async function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 980,
    height: 630,
    frame: false, //标题栏显示隐藏
    resizable: false, //窗口宽高禁止拉动
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, "preload.js")
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    mainWindow.loadURL('app://./index.html')
  }

  const gotTheLock = app.requestSingleInstanceLock(); //禁止启动多次，只打开一个窗口
  if (!gotTheLock) {
    app.quit();
  }
}



//托盘图标
// 主/登录认证
function initTrayIcon() {
  const iconPath = path.join(__dirname, '../static/icon-1.png')
  
  tray = new Tray(iconPath); //引入图标，添加右下角托盘的

  const trayContextMenu = Menu.buildFromTemplate([

    {
      label: "主界面",
      click: () => {
        mainWindow.webContents.send("b", "bark"); //往渲染进程发送操作
      },
    },
    {
      label: "登录认证",
      click: () => {
        mainWindow.webContents.send("auth", "cation"); //往渲染进程发送操作
      },
    },
    {
      label: "显示/隐藏",
      click: () => {
        return mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
      },
    },
  ]);

  tray.setToolTip(setToolsTitle); //设置名字
  tray.setContextMenu(trayContextMenu); //设置这个图标的内容菜单
  //监听任务栏图标的点击事件
  tray.on("click", () => {
    mainWindow.show();
    clearInterval(timer_arr); //取消
    tray.setImage(iconPath);
  });

  Menu.setApplicationMenu(null); //自带File,Edit……,默认为英文 隐藏

  mainWindow.webContents.send("pattern", process.env.NODE_ENV);
}
// 注销或未认证
function initTrayIcon1() {
  const iconPath = path.join(__dirname, '../static/icon-1.png')
  tray = new Tray(iconPath); //引入图标，添加右下角托盘的

  const trayContextMenu = Menu.buildFromTemplate([
    {
      label: "主界面",
      click: () => {
        mainWindow.webContents.send("b", "bark"); //往渲染进程发送操作
      },
    },
    {
      label: "注销认证",
      click: () => {
        mainWindow.webContents.send("cancel", "lation"); //往渲染进程发送操作
      },
    },
    {
      label: "显示/隐藏",
      click: () => {
        return mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
      },
    },
  ]);

  tray.setToolTip(setToolsTitle); //设置名字
  tray.setContextMenu(trayContextMenu); //设置这个图标的内容菜单
  //监听任务栏图标的点击事件
  tray.on("double-click", () => {
    mainWindow.show();
    clearInterval(timer_arr); //取消
    tray.setImage(iconPath);
  });
  Menu.setApplicationMenu(null); //自带File,Edit……,默认为英文 隐藏

  mainWindow.webContents.send("pattern", process.env.NODE_ENV);
}
// 注册
function initTrayIcon2() {
  const iconPath = path.join(__dirname, '../static/icon-1.png')
  tray = new Tray(iconPath); //引入图标，添加右下角托盘的

  const trayContextMenu = Menu.buildFromTemplate([
    {
      label: "注册",
      click: () => {
        mainWindow.show();
      },
    },
  ]);

  tray.setToolTip(setToolsTitle); //设置名字
  tray.setContextMenu(trayContextMenu); //设置这个图标的内容菜单
  Menu.setApplicationMenu(null); //自带File,Edit……,默认为英文 隐藏
}
// 登录
function initTrayIcon3() {
  const iconPath = path.join(__dirname, '../static/icon-1.png')
  tray = new Tray(iconPath); //引入图标，添加右下角托盘的

  const trayContextMenu = Menu.buildFromTemplate([
    {
      label: "登录",
      click: () => {
        mainWindow.show();
      },
    },
  ]);

  tray.setToolTip(setToolsTitle); //设置名字
  tray.setContextMenu(trayContextMenu); //设置这个图标的内容菜单
  Menu.setApplicationMenu(null); //自带File,Edit……,默认为英文 隐藏
}
// 销毁
function initTrayIcon4() {
  tray.destroy();
  tray = null;
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS3_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
  initTrayIcon();
})

// 实现自定义标题栏，最小化，最大化，关闭  接收
ipcMain.on("window-min", () => mainWindow.minimize());
ipcMain.on("window-max", () => {
  if (mainWindow.isMaximized()) {
    mainWindow.restore();
    // mainWindow.unmaximize();
  } else {
    mainWindow.maximize();
  }
});

ipcMain.on("windowLogin", () => {
  initTrayIcon4();
  initTrayIcon3();
});

ipcMain.on("windowInstall", () => {
  initTrayIcon4();
  initTrayIcon2();
});

ipcMain.on("windowHome", () => {
  initTrayIcon4();
  initTrayIcon();
});

// 认证状态
ipcMain.on("Certification-status", () => {
  initTrayIcon4();
  initTrayIcon();
});
// 注销或未认证
ipcMain.on("Not-certified", () => {
  initTrayIcon4();
  initTrayIcon1();
});


// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
